import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { IcartItem } from '@/types/cart'

export const useCart = defineStore('cart', () => {
  const cartData = ref([] as IcartItem[])

  /**
   * 判断有相同的id修改数量，否则新增记录
   */
  const addCartData = (record: IcartItem, bol: boolean = true) => {
    if (cartData.value.find((item) => item.id === record.id)) {
      cartData.value = cartData.value.map((item) => {
        return item.id === record.id
          ? { ...item, num: bol ? item.num + 1 : item.num + record.num }
          : item
      })
    } else {
      cartData.value = [...cartData.value, record]
    }
  }
  const addAllCartData = (records: IcartItem[]) => {
    cartData.value = [...cartData.value, ...records]
  }
  const removeCartData = (record: IcartItem, bol: boolean = true) => {
    if (cartData.value.find((item) => item.id === record.id)) {
      cartData.value = cartData.value.map((item) => {
        return item.id === record.id
          ? { ...item, num: bol ? item.num - 1 : item.num + record.num }
          : item
      })
    } else {
      cartData.value = [...cartData.value, record]
    }
  }

  const onSelectedAll = (val: boolean) => {
    cartData.value = cartData.value.map((item) => {
      return { ...item, checked: val }
    })
  }
  const getSelectedList = () => {
    return cartData.value.filter((item) => {
      return item.checked
    })
  }
  const clearAll = () => {
    cartData.value = []
  }

  const deleteById = (id: string | number) => {
    cartData.value = cartData.value.filter((item) => {
      return item.id !== id
    })
  }
  const checkedHandler = (item: IcartItem) => {
    cartData.value = cartData.value.map((record) => {
      if (item.id === record.id) {
        return { ...record, checked: !record.checked }
      }
      return record
    })
  }

  const getCartData = () => {
    return cartData.value
  }

  // 计算选中总件数
  const getCartTotalNum = () => {
    return cartData.value.reduce((sum, item) => sum + (item.num || 0), 0)
  }

  const getByIdNum = (id: string) => {
    return cartData.value.find((item) => item.id === id)?.num || 0
  }

  const successCartHandler = () => {
    cartData.value = cartData.value.filter((item: IcartItem) => !item.checked)
  }

  return {
    cartData,
    getByIdNum,
    successCartHandler,
    getCartTotalNum,
    getCartData,
    clearAll,
    addAllCartData,
    checkedHandler,
    deleteById,
    getSelectedList,
    onSelectedAll,
    addCartData,
    removeCartData,
  }
})
